package edu.neu.javaweb.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter(
        urlPatterns = {"/pages/*"},
        initParams = { @WebInitParam(name = "excludedExt", value = "jpeg jpg png js css min.js min.css woff woff2") }
)
public class AuthFilter implements Filter {
    final Logger log = LoggerFactory.getLogger(this.getClass().getName());


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        log.info("oh ♂ yeah ♂ do_auth_filter");
        log.info("do_auth_filter");

        // 检测session
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        HttpSession session = httpServletRequest.getSession();
        Object isLoginSession = session.getAttribute("isLogin");

        log.info(httpServletRequest.getServletPath());

        // 检查要去的地方是不是在忽略列表里面
//        if (ignoreUrlList.contains(httpServletRequest.getServletPath())) {
//            // 如果本来是要访问忽略列表里面的，正常去，不过滤了
//            filterChain.doFilter(servletRequest, servletResponse);
//        } else {
            // 否则，进行session验证
            if (isLoginSession != null && (Boolean) isLoginSession) {
                // isLogin有，且为true，认为已经登录
                log.info("已建立的会话 && 已登录: " + session.getAttribute("username") + " " + session.getId());
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                // isLogin 无 或者 为false，认为没登录
                if (isLoginSession == null) {
                    log.info("初次见面: " + session.getId());
                    httpServletRequest.getSession().setAttribute("isLogin", false);
                } else {
                    log.info("已建立的会话 && 未登录: " + session.getId());
                }
                // 跳到登录界面
                log.info("jump to login!");
                httpServletResponse.sendRedirect("../login.html?expired=true");
            }
//        }
    }
}
